<?php 
class Controller_WWW_Payment extends Controller_WWW_Template
{
    public function __construct ($req, $res)
    {
        $this->template = 'smarty:www/payment/pay';
        parent::__construct($req, $res);
    }

    // 选择支付平台(支付宝/微信), 支付transactionId记录
    public function action_pay ($transId)
    {
        $userInfo = Util_User::getUserInfo($this->_uid);
        $this->template->set('info',$userInfo);
        $this->template->set('uid',$this->_uid);
        $this->template->set('transactionId', $transId);
    }

    public function action_return ($transId)
    {
        $trans  = new Payment_Transaction($transId);
        $detail = $trans->detail();
        $this->template->set('transactionId', $transId);
        $this->template->set('transaction', $detail);
        $this->template->set_filename('smarty:www/payment/return');
    }

    // 微信扫码支付（PC版)
    public function action_weixin ($transId)
    {
        $trans  = new Payment_Transaction($transId);
        $detail = $trans->detail();

        $parameter = array(
            "out_trade_no" => Arr::get($detail, 'out_trade_no'),
            "total_fee"    => Arr::get($detail, 'total_fee'),   // 分
            "body"         => Arr::get($detail, 'body'),
            'notify_url'   => url::site('/payment/callback/weixin', 'http'),
        );

        $pay = new Pay_Pay($parameter);
        $imgsrc = $pay->create_pay_order();

        echo json_encode(array('status' => 0, 'imgsrc' => $imgsrc));
        exit;
    }

    // 支付宝支付 (PC版)
    public function action_alipay ($transId)
    { 
        $trans  = new Payment_Transaction($transId);
        $detail = $trans->detail();

        $pay = Paysdk::instance("alipay");
        $parameter = array(
            "out_trade_no" => Arr::get($detail, 'out_trade_no'),
            "total_fee"    => Arr::get($detail, 'total_fee') / 100,   // 元
            "body"         => Arr::get($detail, 'body'),
            "notify_url"   => url::site('/payment/callback/alipay', 'http'),
            "return_url"   => url::site('/payment/return/'.$transId, 'http'),
        );

        $form = $pay->set_info($parameter)->get_form();
        $content =<<<EOF
$form
<script>
var form = document.forms[0];
if (form)
    form.submit();
</script>
<p>跳转中...</p>
EOF;
        echo $content;exit;
    }

    public function action_callback ($type)
    {
        $type = strtoupper($type);
        Kohana::$log->add(Log::DEBUG, "callback_$type: ". print_r($_GET,true) . print_r($_POST,true));
        if ($type == 'WEIXIN')
            $this->notify_weixin ();
        else
            $this->notify_alipay ();
    }

    public function notify_weixin ()
    {
        $notify = new Payment_Weixin_Notify();
        $notify->Handle(false);
    }

    public function notify_alipay ()
    {
        $notify = new Payment_Alipay_Notify();
        if ($notify->Handle(false))
        {
            echo "success";exit;
        }
        else
        {
            echo "fail";exit;
        }
    }

    public function action_notify_refund ()
	{
        require_once(DOCROOT."/resource/alipay_refund/alipay.config.php");
        require_once(DOCROOT."/resource/alipay_refund/lib/alipay_notify.class.php");

        Kohana::$log->add(Log::DEBUG, "ALIPAY_REFUND_NOTIFY:".print_r($_POST, TRUE));
		
		// 计算得出通知验证结果
		$alipayNotify = new AlipayNotify($alipay_config);
		$verify_result = $alipayNotify->verifyNotify();
		
        // 验证成功
		if($verify_result) 
        {
			//请在这里加上商户的业务逻辑程序代
		
			
			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			
		    //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
			
			//批次号
			$batch_no = $_POST['batch_no'];
		
			//批量退款数据中转账成功的笔数
			$success_num = $_POST['success_num'];
		
			//批量退款数据中的详细信息
			$result_details = $_POST['result_details'];
		
		
			// 判断是否在商户网站中已经做过了这次通知返回的处理
			// 如果没有做过处理，那么执行商户的业务程序
			// 如果有做过处理，那么不执行商户的业务程序

            $arr_details = explode('#', $result_details);
            $ret = array();
            foreach ($arr_details as $rs)
            {
                $items = explode('^', $rs);
                $ret[] = array(
                    'transactionId' => $items[0],
                    'moneyYuan'     => $items[1],
                    'codeMsg'       => $items[2],
                );
            }
	    Kohana::$log->add(Log::DEBUG, "ALIPAY REFUND DETAILS:" . print_r($ret, TRUE));

            try {
                $alipay = new Payment_Alipay_Refund();
                $alipay->setResult($ret);
            }
            catch (Exception $e)
            {
                //
            }
		        
			echo "success";exit;		//请不要修改或删除
		
			// 调试用，写文本函数记录程序运行情况是否正常
			// logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
		
			// ——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
		}
		else 
        {
		    //验证失败
		    echo "fail";exit;
		
		    //调试用，写文本函数记录程序运行情况是否正常
		    //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
		}
		
	} // function 
}
